package com.ck.common.utils.security;

import com.ck.common.bean.McApiRsa;
import com.ck.common.bean.McApiUserAuth;
import com.ck.common.constant.Constants;
import com.ck.common.exception.BusinessException;
import com.ck.common.utils.jwt.RedisCache;
import com.ck.common.utils.security.sign.CtAes;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ck
 * @date 2024/1/19 16:16
 */
@Component
@Slf4j
public class RsaUtil {
    private static String isDebug;


    @Value("${isDebug}")
    public void setProfile(String pro) {
        isDebug = pro;
    }

    public static final String CHARSET = "UTF-8";
    public static final String RSA_ALGORITHM = "RSA";

    //生成密钥对，一般来说执行一次就行
    public static Map<String, String> createKeys(int keySize) {
        //为RSA算法创建一个KeyPairGenerator对象（KeyPairGenerator，密钥对生成器，用于生成公钥和私钥对）
        KeyPairGenerator kpg;
        try {
            kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
        }

        //初始化KeyPairGenerator对象,密钥长度
        kpg.initialize(keySize);
        //生成密匙对
        KeyPair keyPair = kpg.generateKeyPair();
        //得到公钥
        Key publicKey = keyPair.getPublic();
        String publicKeyStr = Base64.encodeBase64String(publicKey.getEncoded()); //返回一个publicKey经过二次加密后的字符串
        //得到私钥
        Key privateKey = keyPair.getPrivate();
        String privateKeyStr = Base64.encodeBase64String(privateKey.getEncoded()); //返回一个privateKey经过二次加密后的字符串

        Map<String, String> keyPairMap = new HashMap<String, String>();
        keyPairMap.put("publicKey", publicKeyStr);
        keyPairMap.put("privateKey", privateKeyStr);

        return keyPairMap;
    }

    /**
     * 得到公钥
     *
     * @param publicKey 密钥字符串（经过base64编码）
     * @throws Exception
     */
    public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过X509编码的Key指令获得公钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        return key;
    }

    /**
     * 得到私钥
     *
     * @param privateKey 密钥字符串（经过base64编码）
     * @throws Exception
     */
    public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过PKCS#8编码的Key指令获得私钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
        return key;
    }

    /**
     * 公钥加密
     *
     * @param data
     * @param publicKey
     * @return
     */
    public static String publicEncrypt(String data, RSAPublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return Base64.encodeBase64String(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥解密
     *
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateDecrypt(String data, RSAPrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥加密
     *
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateEncrypt(String data, RSAPrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            return Base64.encodeBase64String(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 公钥解密
     *
     * @param data
     * @param publicKey
     * @return
     */

    public static String publicDecrypt(String data, RSAPublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET);
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
        int maxBlock = 0;
        if (opmode == Cipher.DECRYPT_MODE) {
            maxBlock = keySize / 8;
        } else {
            maxBlock = keySize / 8 - 11;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] buff;
        int i = 0;
        try {
            while (datas.length > offSet) {
                if (datas.length - offSet > maxBlock) {
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                } else {
                    buff = cipher.doFinal(datas, offSet, datas.length - offSet);
                }
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            }
        } catch (Exception e) {
            throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
        }
        byte[] resultDatas = out.toByteArray();
        IOUtils.closeQuietly(out);
        return resultDatas;
    }

    /**
     * 对登录请求报进行解密
     *
     * @return
     */
    public static String decryptReqDataLogin(String encryptData, String keyToken, RedisCache redisCache) throws Exception {

        // 开发模式,取消加解密
        if ("Y".startsWith(isDebug)) {
            return encryptData;
        }

        if (StringUtils.isEmpty(encryptData) || StringUtils.isEmpty(keyToken)) {
            return "";
        }

        String cacheKey = Constants.RedisKey.PUBLIC_KEY+keyToken;
        // 登录接口
        McApiRsa mcApiRsa = redisCache.getCacheObject(cacheKey);
        if(mcApiRsa == null){
            throw new BusinessException("秘钥过期，请刷新后重试");
        }

        String deData = RsaUtil.privateDecrypt(encryptData, RsaUtil.getPrivateKey(mcApiRsa.getPrivateKey()));
        return deData;
    }


    /**
     * 对登录后返回给前端的加密内容进行加密传输
     *
     * @param respJsonStr
     * @param loginAes
     * @param redisCache
     * @return
     */
    public static String encodeRespData(String respJsonStr, CtAes loginAes, String keyToken, RedisCache redisCache) {
        // 开发模式,取消加解密
        if ("Y".startsWith(isDebug)) {
            return respJsonStr;
        }

        if (StringUtils.isEmpty(respJsonStr)) {
            return "";
        }
        // 返回的数据
        String respTxt = "";
        // 登录接口
        if (loginAes != null) {
            respTxt = loginAes.encrypt(respJsonStr);
        } // 除登录接口外的其他接口
        else if (!StringUtils.isEmpty(keyToken)) {
            McApiUserAuth cacheObject =(McApiUserAuth) redisCache.getCacheObject(keyToken);
            CtAes ctAes = new CtAes(cacheObject.getAesInfo().getAesKey(), cacheObject.getAesInfo().getVipara());
            respTxt = ctAes.encrypt(respJsonStr);
        }

        return respTxt;
    }


    /**
     * 对业务请求报文进行解密
     *
     * @return
     */
    public static String decryptReqData(String encryptData, String keyToken, RedisCache redisCache,Long userId) throws Exception {
        // 开发模式,取消加解密
        if ("Y".startsWith(isDebug)) {
            return encryptData;
        }

        if (StringUtils.isEmpty(encryptData) || StringUtils.isEmpty(keyToken)) {
            return "";
        }
        String aesKey=null;
        String vipara=null;
        //获取Aes业务信息得到秘钥和偏移量
        String cacheKey="Auth:" + userId + ":keyToken:";
        Object cacheObject = redisCache.getCacheObject(cacheKey + keyToken);
        if (cacheObject instanceof McApiUserAuth){
            McApiUserAuth mcApiUserAuth =(McApiUserAuth) cacheObject;
            aesKey = mcApiUserAuth.getAesInfo().getAesKey();
            vipara = mcApiUserAuth.getAesInfo().getVipara();
            log.info("秘钥信息: " + mcApiUserAuth.toString());
        }
        //Aes解密
        CtAes ctAes = new CtAes(vipara,aesKey);
        return ctAes.decrypt(encryptData);
    }


    //测试
    public static void main(String[] args) throws Exception {
//        //生成公私钥
//        Map<String, String> keyMap = RsaUtil.createKeys(512);
//        //公钥
//        String publicKey = keyMap.get("publicKey");
//        //私钥
//        String privateKey = keyMap.get("privateKey");

//        String privateKey="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJ8Y5kBIV4k5ImFdtTnfqN+NDdcOpShKUNbOssySSq4+29/WSgiNUn7PjaHGuvzLY4AKe8YuiQ6hLpNlLt+8hIeIivnm0tC7HNWnxsFV3dM0wE7QDb2ticXqmn5a/iLLplEWq38SQDYjT0VOY/lipq//tZtRdh8Tzc9WcBReBPizAgMBAAECgYBBqV0eGr1F/TabSLmK8SwZV3Xm1DyFrGZAwX45wAbicz772s0jSnBJtg+WPRbfTnH6XllHKd2XFB7M5m26GWv4fGfxbP7rw6up8yaZ3tZSPkq/eLu+UUU4MYL9Y866XEkYYrQNOlE/OaXkDaHWs2ee30vpYZUhCDmWE0QpRsm5QQJBAOD+5Ds5FO8SgLG27G3MOftcSl+vd2bPlIHHUij7k3FnAFYYdtHGAmQPKNrhaX0G0eLBLOicajUtbQHtizc4rR0CQQC1BVQXHaA2ICk1NG5o3Kl1sKoTSAXLH5CFuAAjqRRb9MP1O0bPS2TvldhFuJVMikREEwO/aMmQw682gTSfieQPAkBewru5PbdVYYOWVaaKL+OTvDEOz8YIJRE0/4/Y9uwIbQs1N6SDgVPsdH4OgbV+FOs9B4M0jPwmXXV1xGhH37T5AkEAgjskJUE2GtqGavWenShrbfU8VoTRTjIWOm2HBCDHOeTc+de8eLQoGMm3/2jtWFR9CnCXmKRdpx1xN4g7ALAmdwJANrDb4BBHrjHrdqcUZ6WYmW4LqbajSybj4HTEEUAkW3wucmSG+megJ1Mws2HlGH90hGb2q9aWg/VcwNdZqlhU9g==";
        String publicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChtbkPLedDWf/c31RoYqzLSA8r3mfG535WnOSHOseILxGN1ZXo7OsLOnxK/aRzJBBoTj2kvdPb7Q3lnGjysdISln86jIp2tiMWAg9BtBOgXEP3Dc7C5aMXFZv38XChgBTtunkGSb/M33urp5x85OehqDrH2Hy/i2kSEbyPVHvlqQIDAQAB";
        String d="{\"loginName\":\"ck\",\"pwd\":\"123456\"}";
        //对内容进行公钥加密
        String encodedData = RsaUtil.publicEncrypt(d, RsaUtil.getPublicKey(publicKey));
        System.out.println("公钥加密密文：" + encodedData);
//        //用私钥对密文进行解密
//        String decodedData = RsaUtil.privateDecrypt(encodedData, RsaUtil.getPrivateKey(privateKey));
//        System.out.println("解密后文字: " + decodedData);
    }
}
